package com.runmi.webchat.aftersale.common.utils;

import java.net.URLEncoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * 
 * DES操作工具类
 * @author 李云锋
 * @date 2014-09-23
 */
public class DESUtil {
	
	
	protected static final Log log = LogFactory.getLog(DESUtil.class.getSimpleName());
	//protected static Logger log = Logger.getLogger(DESUtil.class);
	
	public static String decryptKey = "kdd4bbea"; // 密钥
	//public static String decryptKey = CatergoryHelper.getCatergoryServer(ApiCatergoryHelper.LOGIN_DECRYPT_KEY); // 密钥
	public static byte[] iv = { 13, 8, 3, 16, 23, 6, 11, 5 };  //向量
	
	//DES解密
	public static String decryptDES(String encryptString) throws Exception {
		if(encryptString==null || "".equals(encryptString)){
			return encryptString;
		}
		try {
//			encryptString = URLDecoder.decode(encryptString, "UTF-8");
			
			byte str2[] = Base64.decodeBase64(encryptString.getBytes("UTF-8"));
			IvParameterSpec zeroIv = new IvParameterSpec(iv);
			SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes("UTF-8"), "DES");
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
			byte[] str3 = cipher.doFinal(str2);
			String res = encryptString;
			if (str3 != null) {
				res = new String(str3, "UTF-8");
			}
			//System.out.println(encryptString + " 解密结果: " + res);
			return res;
		} catch (Exception e) {
			log.error("解密失败：" + encryptString,e);
			throw  e;
		}
	}
	
	public static String encryptDES(String encryptString) throws Exception {
		byte[] iv = { 13, 8, 3, 16, 23, 6, 11, 5 };  //向量
		String encryptKey = "kdd4bbea";
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes("UTF-8"), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
		byte[] temp = Base64.encodeBase64(encryptedData, false);
		String secret = URLEncoder.encode(new String(temp), "UTF-8");
		return secret;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(DESUtil.encryptDES("123123"));
		System.out.println(DESUtil.decryptDES(DESUtil.encryptDES("123123")));
	}
}
